# !/usr/bin/env python3

import re
import os
import sys
from pprint import pprint

from _internal import (
    get_repo_root,
    execute,
)


def handler_cppcheck(args):
    root = get_repo_root()
    if root is None:
        print("ERROR: Failed reading git folder.")
        exit(10000)

    try:
        os.chdir(root)
    except IOError:
        print("ERROR: Failed changing directory to %s" % (root))
        exit(10001)

    code = -1

    try:
        folder_to_check = args.target
    except AttributeError:
        folder_to_check = []

    folder_list = []
    if not args.target:
        if args.prjfile and os.path.isfile(args.prjfile):
            os.environ["CPPCHECK_PROJECT"] = args.prjfile
        # else 使用 plugin-cppcheck-folders.txt 中的设置
    else:
        folder_list = args.target

    try:
        code, _, _ = execute(
            [".plugins/plugin-cppcheck.sh", args.level,] + folder_list)
    except FileNotFoundError:
        print("ERROR: Failed executing cppcheck")
        exit(10004)

    if code != 0:
        print("ERROR: Failed executing cppcheck")

    exit(code)


def add_parser(subparsers):
    '''
    add a sub-command parser.
    '''
    root = get_repo_root()
    if root is None:
        return

    cmd_parser = subparsers.add_parser('cppcheck', help='static code check')
    cmd_parser.set_defaults(func=handler_cppcheck)

    cmd_parser.add_argument("-l",  "--level",
                            dest="level",
                            choices=["all", "warning", "style"],
                            default="warning",
                            help="cppcheck level of report.")

    cmd_parser.add_argument("--prjfile",
                            dest="prjfile",
                            default=None,
                            help="compile options command")

    cmd_parser.add_argument(dest="target",
                            nargs="*",
                            default=[],
                            help="target folder to be checked.")
